import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { Teacher } from '@/types';

interface AuthState {
  token: string | null;
  teacher: Teacher | null;
  isAuthenticated: boolean;
}

const initialState: AuthState = {
  token: localStorage.getItem('token'),
  teacher: localStorage.getItem('teacher') ? JSON.parse(localStorage.getItem('teacher')!) : null,
  isAuthenticated: !!localStorage.getItem('token'),
};

export const authSlice = createSlice({
  name: 'auth',
  initialState,
  reducers: {
    login: (state, action: PayloadAction<{ token: string; teacher: Teacher }>) => {
      const { token, teacher } = action.payload;
      state.token = token;
      state.teacher = teacher;
      state.isAuthenticated = true;
      localStorage.setItem('token', token);
      localStorage.setItem('teacher', JSON.stringify(teacher));
    },
    logout: (state) => {
      state.token = null;
      state.teacher = null;
      state.isAuthenticated = false;
      localStorage.removeItem('token');
      localStorage.removeItem('teacher');
      localStorage.removeItem('csrfToken');
    },
    updateTeacher: (state, action: PayloadAction<Teacher>) => {
      state.teacher = action.payload;
      localStorage.setItem('teacher', JSON.stringify(action.payload));
    },
  },
});

export const { login, logout, updateTeacher } = authSlice.actions;
export default authSlice.reducer; 